今天接續昨天,調整卡片樣式。
目標樣式:
參考 MD3 Card
日期我們使用 title medium
內文使用 body medium
在 Text() 設定參數 style 打上 style =,MT+Enter 選擇MaterialTheme(android.compose.Material3) ,然後選擇引用字體 typography ,選擇字體樣式 titleMedium 還有 bodyMedium
Card() {
Column(
modifier = Modifier.padding(16.dp)
) {
Text(
text = training.date.toString(),
style = MaterialTheme.typography.titleMedium
)
Text(
text = training.trainingContext,
style = MaterialTheme.typography.bodyMedium
)
}
}

設計上有放一個圓邊的裝飾底色給日期用,這裡我用Card 來實踐。首先用Card+Tab 生成Card,再來設定邊緣形狀,這裡有個小技巧可以使用 CircleShape 來自造Card 左右兩側的弧度是50的效果,如果在CircleShape 上ctrl+B 可以看到設定邊角圓弧被定為50RoundedCornerShape(50) ,這樣以後想要調整圓弧大小也可以直接用50RoundedCornerShape 來達成。
再來設定Card 底色,Card 上 ctrl+B 來看預設顏色CardDefaults.cardColors() 直接複製起來用。
CardDefaults.cardColors() +ctrl+B 觀察參數,我要改的是卡片底色 containerColor ,回到Card 設定containerColor = Color.Gray (這裡還沒決定要用什麼顏色,先用灰色加上 TODO來做提醒。
Card(
shape = CircleShape,
colors = CardDefaults.cardColors(containerColor = Color.Gray) //TODO check color
) {
Text(
text = training.date.toString(),
style = MaterialTheme.typography.titleMedium,
)
}

要讓字體置中,可以將 Text 的範圍撐到最大使用 modifier = Modifier.fillMaxWidth() 。
再來調整 Align ,Text + Ctrl+B 找到參數叫做textAlign ,型態是TextAlign 。回來設置
textAlign = TextAlign.Center 。
Card(
shape = CircleShape,
colors = CardDefaults.cardColors(containerColor = Color.Gray)
) {
Text(
text = training.date.toString(),
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center, //++
modifier = Modifier.fillMaxWidth() //++
)
}

接下來調整一下日期卡片和內文之間的距離。設置Text 的Modifier ,用 padding 的 top 參數設為 8.dp 。
Text(
text = training.trainingContext,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(top = 8.dp) //++
)

日期格式使用DateTimeFormatter.ofPattern() ,第一個參數是日期樣式可以參考 JAVA Doc ,常用的有 yyyy代表年、 MM 代表月份、 dd 代表幾號。第二個參數設定時區 Locale.TAIWAN ,這樣才能正確顯示星期幾。
val formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd (E)", Locale.TAIWAN)
將 formatter 帶入 LocalDate , LocalDate.format(formatter)
Card(
shape = CircleShape,
colors = CardDefaults.cardColors(containerColor = Color.Gray)//TODO check color
) {
Text(
~~text = training.date.toString(),~~
text = training.date.format(formatter),
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
}

今天用到了Card 來作為底部裝飾,學會了CircleShape來設定Card的邊角。
用Modifier.fillMaxWidth() 將字體內容展開到最寬,配合上TextAlign.Center 做到置中效果。
最後用到日期格式 DateTimeFormatter.ofPattern() 將LocalDate 設定成想要的格式。
今日運動:
休息